#!/usr/bin/env node

/**
 * 小红猫DPS统计工具 - 简化构建脚本
 * 专门解决图标问题
 */

const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

class SimpleBuilder {
    constructor() {
        this.projectDir = __dirname;
        this.distDir = path.join(this.projectDir, 'dist');
        this.tempDir = path.join(this.projectDir, 'temp_build');
        this.version = '2.3.12';
        this.iconPath = path.join(this.projectDir, 'redcat.ico');
        
        this.ensureDirectories();
    }

    log(message) {
        console.log(`[BUILD] ${message}`);
    }

    ensureDirectories() {
        [this.distDir, this.tempDir].forEach(dir => {
            if (!fs.existsSync(dir)) {
                fs.mkdirSync(dir, { recursive: true });
            }
        });
    }

    clean() {
        this.log('清理构建目录...');
        try {
            if (fs.existsSync(this.distDir)) {
                fs.rmSync(this.distDir, { recursive: true, force: true });
            }
            if (fs.existsSync(this.tempDir)) {
                fs.rmSync(this.tempDir, { recursive: true, force: true });
            }
            this.ensureDirectories();
            this.log('✅ 构建目录清理完成');
        } catch (err) {
            this.log(`❌ 清理失败: ${err.message}`);
        }
    }

    prepareBuildFiles() {
        this.log('准备构建文件...');
        
        // 复制必要的文件到临时目录
        const filesToCopy = [
            'app.js',
            'server.js',
            'server_wrapper.js',
            'create_config.js',
            'analyze_output.js',
            'package.json',
            'skill_names.json',
            'skill_names_v2.json',
            'nicknames.json'
        ];

        filesToCopy.forEach(file => {
            const srcPath = path.join(this.projectDir, file);
            const destPath = path.join(this.tempDir, file);
            if (fs.existsSync(srcPath)) {
                fs.copyFileSync(srcPath, destPath);
                this.log(`✅ 复制: ${file}`);
            }
        });

        // 复制目录
        const dirsToCopy = ['public', 'algo'];
        dirsToCopy.forEach(dir => {
            const srcDir = path.join(this.projectDir, dir);
            const destDir = path.join(this.tempDir, dir);
            if (fs.existsSync(srcDir)) {
                this.copyDirectory(srcDir, destDir);
                this.log(`✅ 复制目录: ${dir}`);
            }
        });

        // 复制悬浮窗文件
        const overlayDir = path.join(this.projectDir, 'floating_overlay');
        const overlayDestDir = path.join(this.tempDir, 'floating_overlay');
        if (fs.existsSync(overlayDir)) {
            this.copyDirectory(overlayDir, overlayDestDir);
            this.log(`✅ 复制目录: floating_overlay`);
        }

        this.log('✅ 构建文件准备完成');
    }

    copyDirectory(src, dest) {
        if (!fs.existsSync(dest)) {
            fs.mkdirSync(dest, { recursive: true });
        }

        const entries = fs.readdirSync(src, { withFileTypes: true });
        
        for (const entry of entries) {
            const srcPath = path.join(src, entry.name);
            const destPath = path.join(dest, entry.name);
            
            if (entry.isDirectory()) {
                this.copyDirectory(srcPath, destPath);
            } else {
                fs.copyFileSync(srcPath, destPath);
            }
        }
    }

    async buildExecutable() {
        this.log('开始打包可执行文件...');
        try {
            const exeName = `小红猫DPS-v${this.version}.exe`;
            const outputPath = path.join(this.distDir, exeName);
            const entryPath = path.join(this.tempDir, 'app.js');

            // 检查图标文件
            if (!fs.existsSync(this.iconPath)) {
                this.log('⚠️ 警告：找不到 redcat.ico 文件，将使用默认图标');
            } else {
                this.log(`✅ 找到图标文件: ${this.iconPath}`);
            }

            // 使用 pkg 打包
            const assetPatterns = [
                'public/**/*',
                'floating_overlay/**/*',
                'algo/**/*',
                'skill_names*.json',
                'nicknames.json',
                'skill_names.json',
                'package.json',
                'server.js',
                'server_wrapper.js',
                'create_config.js',
                'analyze_output.js'
            ];

            const assetsFlags = assetPatterns.map(p => `--assets ${p}`).join(' ');

            const pkgCommand = [
                'pkg',
                entryPath,
                '--target', 'node18-win-x64',
                '--output', outputPath,
                assetsFlags
            ].join(' ');

            this.log(`执行打包命令: ${pkgCommand}`);
            execSync(pkgCommand, { 
                cwd: this.tempDir, 
                stdio: 'inherit',
                maxBuffer: 1024 * 1024 * 10
            });

            if (fs.existsSync(outputPath)) {
                const stats = fs.statSync(outputPath);
                const fileSizeMB = (stats.size / 1024 / 1024).toFixed(2);
                this.log(`✅ 打包成功: ${exeName} (${fileSizeMB} MB)`);

                // 尝试设置图标
                if (fs.existsSync(this.iconPath)) {
                    await this.setExeIcon(outputPath);
                }

                return outputPath;
            } else {
                throw new Error('打包后未找到输出文件');
            }
        } catch (err) {
            this.log(`❌ 打包失败: ${err.message}`);
            throw err;
        }
    }

    async setExeIcon(exePath) {
        this.log('正在设置exe图标...');
        try {
            // 尝试使用 rcedit
            const rceditPath = path.join(this.projectDir, 'node_modules', '.bin', 'rcedit.exe');
            
            if (fs.existsSync(rceditPath)) {
                execSync(`"${rceditPath}" "${exePath}" --set-icon "${this.iconPath}"`, { 
                    stdio: 'inherit',
                    timeout: 30000
                });
                this.log('✅ 图标设置成功 (rcedit)');
                return;
            }

            // 尝试使用全局 rcedit
            try {
                execSync(`rcedit "${exePath}" --set-icon "${this.iconPath}"`, { 
                    stdio: 'inherit',
                    timeout: 30000
                });
                this.log('✅ 图标设置成功 (全局rcedit)');
                return;
            } catch (e) {
                this.log(`⚠️ 全局rcedit失败: ${e.message}`);
            }

            // 尝试使用 npx
            try {
                execSync(`npx rcedit "${exePath}" --set-icon "${this.iconPath}"`, { 
                    stdio: 'inherit',
                    timeout: 30000
                });
                this.log('✅ 图标设置成功 (npx rcedit)');
                return;
            } catch (e) {
                this.log(`⚠️ npx rcedit失败: ${e.message}`);
            }

            this.log('⚠️ 所有图标设置方法都失败，exe将使用默认图标');
        } catch (err) {
            this.log(`⚠️ 图标设置失败: ${err.message}`);
        }
    }

    cleanup() {
        this.log('清理临时文件...');
        try {
            if (fs.existsSync(this.tempDir)) {
                fs.rmSync(this.tempDir, { recursive: true, force: true });
            }
            this.log('✅ 临时文件清理完成');
        } catch (err) {
            this.log(`⚠️ 临时文件清理失败: ${err.message}`);
        }
    }

    showResults() {
        this.log('\n' + '='.repeat(60));
        this.log('构建完成！');
        this.log('='.repeat(60));
        
        const distFiles = fs.readdirSync(this.distDir);
        
        this.log('生成的文件:');
        distFiles.forEach(file => {
            const filePath = path.join(this.distDir, file);
            const stats = fs.statSync(filePath);
            const sizeMB = (stats.size / 1024 / 1024).toFixed(2);
            this.log(`  📦 ${file} (${sizeMB} MB)`);
        });

        this.log('\n发布说明:');
        this.log('  1. exe文件可直接运行，无需安装');
        this.log('  2. 首次运行需要管理员权限');
        this.log('  3. 程序会自动检测和修复环境问题');
        this.log('  4. 支持离线运行（除了依赖下载）');
        
        if (fs.existsSync(this.iconPath)) {
            this.log('  5. 图标设置已尝试，如果未生效请检查防病毒软件');
        }
        
        this.log('\n' + '='.repeat(60));
    }

    async build() {
        try {
            console.log(`🚀 开始构建 小红猫DPS统计 v${this.version}\n`);

            // 1. 清理
            this.clean();

            // 2. 准备文件
            this.prepareBuildFiles();

            // 3. 打包可执行文件
            const exePath = await this.buildExecutable();

            // 4. 清理临时文件
            this.cleanup();

            // 5. 显示结果
            this.showResults();

        } catch (err) {
            this.log(`\n❌ 构建失败: ${err.message}`);
            this.cleanup();
            process.exit(1);
        }
    }
}

// 运行构建
const builder = new SimpleBuilder();
builder.build();
